package models;

import play.db.jpa.JPA;

import javax.persistence.*;
import javax.persistence.criteria.*;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * Created by xuyang on 2017/6/13.
 */
@Entity(name = "public.\"TA014\"")
public class TA014 extends BeamModel {

    @Column(name = "\"SPLIT_TEMPLATE_NAME\"")
    public String split_template_name;

    @Column(name = "\"AVIATION\"")
    public String aviation;

    @Column(name = "\"DEPARTMENT\"")
    public String department;

    @Column(name = "\"SIGNER\"")
    public String signer;

    @Column(name = "\"MARKER\"")
    public String marker;

    @Column(name = "\"MARKER_POS\"")
    public String marker_pos;

    @Column(name = "\"SMI\"")
    public String smi;

    @Column(name = "\"TYPE\"")
    public String type;

    @Column(name = "\"TEMPLATE\"")
    public String template;

    @Temporal(TemporalType.TIMESTAMP)
    @Column(name = "\"LAST_UPDATE\"", columnDefinition= "TIMESTAMP")
    public Date last_update;

    @OneToMany(mappedBy = "split_template",fetch = FetchType.LAZY)
    public List<TA015> reformat_templates;

    @ManyToMany(mappedBy = "split_templates")
    public List<TB005> aircrafts;

    @Transient
    public int rank;

    @PrePersist
    void createdAt() {
        this.last_update = new Date();
    }

    @PreUpdate
    void updatedAt() {
        this.last_update = new Date();
    }

    public static List<TA014> filterBy(String name, String aircraft, String smi, String type, int limit) {
        EntityManager em = JPA.em();
        CriteriaBuilder cb = em.getCriteriaBuilder();
        CriteriaQuery<TA014> query = cb.createQuery(models.TA014.class);
        Root<TA014> root = query.from(models.TA014.class);

        final List<Predicate> predicates = new ArrayList<Predicate>();

        if (aircraft != null && !aircraft.isEmpty()) {
            Join<TA014, TB005> ac = root.join("aircrafts", JoinType.LEFT);
            predicates.add(cb.like(ac.<String>get("aircraft_id"), "%"+aircraft+"%"));
        }

        if (name != null && !name.isEmpty()) {
            predicates.add(cb.like(root.<String>get("split_template_name"), "%"+name+"%"));
        }

        if (smi != null && !smi.isEmpty()) {
            predicates.add(cb.like(root.<String>get("smi"), "%"+smi+"%"));
        }

        if (type != null && !type.isEmpty()) {
            type = type.toUpperCase();
            predicates.add(cb.equal(root.get("type"), type));
        }

        query.select(root);
        query.where(cb.and(predicates.toArray(new Predicate[predicates.size()])))
                .orderBy(cb.asc(root.<String>get("split_template_name")));

        TypedQuery tQuery = em.createQuery(query);
        if (limit > -1) {
            tQuery.setMaxResults(limit);
        }
        List<models.TA014> items = tQuery.getResultList();

        return items;
    }
}
